# -*- coding: utf-8 -*-
import os
import requests
import json

import sys


class BaiduTrans(object):
    def __init__(self, word):
        self.url = 'http://fanyi.baidu.com/v2transapi'
        self.post_data = {
            'from': 'zh',
            'to': 'en',
            'query': word,
            'transtype': 'translang',
            'simple_means_flag': '3',
            'sign': '',
            'token': ''
        }
        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}

    def get_data(self):
        _user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)
        # TODO 解析Sign、Token
        _response = requests.post(self.url, headers=_user_agent, data=self.post_data)

        return _response.content.decode()

    def parse_data(self, data):
        print(data)
        _result = json.loads(data)['trans_result']['data'][0]['dst']
        print(_result)

    def run(self):
        _data = self.get_data()
        self.parse_data(_data)


def main():
    word = input('请输入查询的单词: ')
    trans = BaiduTrans(word)
    trans.run()


if __name__ == '__main__':
    main()
